//
//  RJCStationHelper.m
//  AirQuality
//
//  Created by Po on 15/8/31.
//  Copyright © 2015年 Po. All rights reserved.
//

#import "RJCStationHelper.h"
@interface RJCStationHelper ()

@end

@implementation RJCStationHelper
- (instancetype)init
{
    self = [super init];
    if (self) {
        _model = [[RJCStationModel alloc] init];
        _model.currentStationCode = @"1001C";
        _model.currentCityName = @"成都";
    }
    return self;
}

- (void)setStationData:(NSString *)stationCode stationName:(NSString *)stationName cityName:(NSString *)cityName
{
    _model.currentStationCode = stationCode;
    _model.currentStationName = stationName;
    _model.currentCityName = cityName;
}

- (void)doOneceNetRequestbasicBlock:(void(^)(BOOL result))basicBlock
                       weatherBlock:(void(^)(BOOL result))weatherBlock
                          lineBlock:(void(^)(BOOL result))lineBlock
{
    //获取仪器数据
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].GetCStationBasicData data:@{} completeBlock:^(id responseObject) {
        if (!(responseObject[@"result"])) {
            basicBlock(NO);
        } else {
            NSArray * columns = responseObject[@"data"];
            NSMutableDictionary * allData = [NSMutableDictionary dictionary];
            for (NSDictionary * dic in columns) {
                NSDictionary * detailDic = [dic allValues][0];
                NSString * stationCode = detailDic[@"STATIONCODE"];
                [allData setObject:detailDic forKey:stationCode];
            }
            [self updateBasicModel:allData];
            basicBlock(YES);
        }
    } failBlack:^(id response) {
        basicBlock(NO);
    }];
    
    //获取最近24消失数据
    NSString * startTime = [RJTools getTimeWithFormat:@"yyyy-MM-dd HH:mm:ss" time:[NSDate dateWithTimeIntervalSinceNow:-(24*60*60)]];
    NSString * endTime = [RJTools getTimeWithFormat:@"yyyy-MM-dd HH:mm:ss" time:[NSDate dateWithTimeIntervalSinceNow:-(60*60)]];
    
    [RJNetWork myNetRequestWithAddress:[NetURL defaultURL].GetCStation24HourData data:@{@"stationcode":_model.currentStationCode,@"starttime":startTime,@"endtime":endTime} completeBlock:^(id responseObject) {
        if (responseObject[@"result"]) {
            NSDictionary * columns = [[responseObject[@"data"][0] allObjects] lastObject];
            NSDictionary * cityColumns = [[[responseObject[@"data"] lastObject] allObjects] lastObject];
            NSArray * stationData = columns[@"STATIONDATA"];
            NSArray * cityData = cityColumns[@"STATIONDATA"];
            [self setLineData:stationData];
            [self setCityData:cityData];
            lineBlock(YES);
        } else {
            lineBlock(NO);
        }
    } failBlack:^(id response) {
        lineBlock(NO);
    }];
    
    //获取天气
    [self doNetRequestWeatherBlock:weatherBlock];
    
}

- (void)updateBasicModel:(NSDictionary *)data
{
    NSMutableArray * tempArray = [NSMutableArray array];
    NSArray * allKeys = [data allKeys];
    allKeys = [allKeys sortedArrayUsingSelector:@selector(compare:)];
    for (NSString * key in allKeys) {
        NSDictionary * tempDic = data[key];
        [tempArray addObject:@{key:@[tempDic[@"STATIONNAME"],tempDic[@"CITYNAME"]]}];
    }
    _model.stations = [NSArray arrayWithArray:tempArray];
    
    NSDictionary * dic = data[_model.currentStationCode];
    _model.currentCityName = dic[@"CITYNAME"];
    _model.currentStationName = dic[@"STATIONNAME"];
    
    NSArray * rankArray = @[@"优",@"良",@"轻度",@"中度",@"重度",@"严重"];
    if (([dic[@"AQI"] integerValue] + 1) / 50 > 5) {
        _model.aqiRankValue = rankArray[5];
    }else{
      _model.aqiRankValue = rankArray[([dic[@"AQI"] integerValue] + 1) / 50];
    }
    
//    _model.ipm25Value = [self getStringWithNum:dic[@"IPM2_5"]];
//    _model.ipm10Value = [self getStringWithNum:dic[@"IPM10"]];
//    _model.iso2Value = [self getStringWithNum:dic[@"ISO2"]];
//    _model.ino2Value = [self getStringWithNum:dic[@"INO2"]];
//    _model.io3Value = [self getStringWithNum:dic[@"IO3"]];
//    _model.icoValue = [self getStringWithNum:dic[@"ICO"]];
    
    _model.pm25Value = [self getStringWithNum:dic[@"PM2_5"]];
    _model.pm10Value = [self getStringWithNum:dic[@"PM10"]];
    _model.so2Value = [self getStringWithNum:dic[@"SO2"]];
    _model.no2Value = [self getStringWithNum:dic[@"NO2"]];
    _model.o3Value = [self getStringWithNum:dic[@"O3"]];
    _model.coValue = [self getStringWithNum:dic[@"CO"]];
    
    _model.visibilityValue = [self getStringWithNum:dic[@"VI"]];
    _model.windDirectionValue = [self getStringWithNum:dic[@"WD"]];
    _model.windSpeedValue = [self getStringWithNum:dic[@"WS"]];
    
    NSString * press = GetStringWithNum(dic[@"PRESS"]);
    _model.pressureValue = (press ?[NSString stringWithFormat:@"%.2f",[press floatValue]] : @"-");
    NSString * hum = GetStringWithNum(dic[@"HUM"]);
    _model.humidnessValue = (hum ? [NSString stringWithFormat:@"%.2f",[hum floatValue]] : @"-");
}

- (NSString *)getStringWithNum:(NSNumber *)num
{
    return (num ? GetStringWithNum(num) : @"-");
}

- (void)doNetRequestWeatherBlock:(void(^)(BOOL result))weatherBlock
{
    NSString * pinyin;
    if ([_model.currentCityName isEqualToString:@"成都"] || [_model.currentCityName isEqualToString:@"成都市"]) {
        pinyin = @"chengdu";
    } else {
        pinyin = [RJTools getPinyinOfString:_model.currentCityName];
    }
    NSString * cityPinYin = [NSString stringWithFormat:@"citypinyin=%@",pinyin];
    [self request:[NetURL defaultURL].GetWeather withHttpArg:cityPinYin weatherBlock:weatherBlock];
}


-(void)request:(NSString*)httpUrl
   withHttpArg:(NSString*)HttpArg
  weatherBlock:(void(^)(BOOL result))weatherBlock{
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: @"d97e2291a23c28c967b29b4ec7a47763" forHTTPHeaderField: @"apikey"];
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                               if (error) {
                                   weatherBlock(NO);
                               } else {
                                   NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                                   if (dic) {
                                       [self setWeatherData:dic];
                                       weatherBlock(YES);
                                   } else {
                                       weatherBlock(NO);
                                   }
                               }
                           }];
}

- (void)setWeatherData:(NSDictionary *)dic
{
    NSDictionary * resData = dic[@"retData"];
    if (resData.count == 0) {
        _model.weatherValue = @"-";
        _model.temValue = @"-";
        return;
    }
    _model.weatherValue = resData[@"weather"];
    _model.temValue = resData[@"temp"];
}

- (void)setLineData:(NSArray *)stationData
{
    @autoreleasepool {
        NSMutableArray * aqiArray = [NSMutableArray array];
        NSMutableArray * pm25Array = [NSMutableArray array];
        NSMutableArray * pm10Array = [NSMutableArray array];
        NSMutableArray * so2Array = [NSMutableArray array];
        NSMutableArray * no2Array = [NSMutableArray array];
        NSMutableArray * coArray = [NSMutableArray array];
        NSMutableArray * o3Array = [NSMutableArray array];
        NSMutableArray * timeArray = [NSMutableArray array];
        
        for (NSInteger i = 0; i < stationData.count ; i ++) {
            NSDictionary * tempDic = stationData[i];
            NSDictionary * dic = [[tempDic allValues] lastObject];
            [aqiArray addObject:(dic[@"AQI"] ? dic[@"AQI"] : @0)];
            [pm25Array addObject:(dic[@"PM2_5"] ? dic[@"PM2_5"] : @0)];
            [pm10Array addObject:(dic[@"PM10"] ? dic[@"PM10"] : @0)];
            [o3Array addObject:(dic[@"O3"] ? dic[@"O3"] : @0)];
            [so2Array addObject:(dic[@"SO2"] ? dic[@"SO2"] : @0)];
            [no2Array addObject:(dic[@"NO2"] ? dic[@"NO2"] : @0)];
            [coArray addObject:(dic[@"CO"] ? dic[@"CO"] : @0)];
            NSTimeInterval time = [dic[@"TIMEPOINT"] integerValue] / 1000;
            NSString * timeString = [RJTools getTimeWithFormat:@"HH时" time:[NSDate dateWithTimeIntervalSince1970:time]];
            [timeArray addObject:timeString];
        }
        
        _model.lineData = @{@"aqi":aqiArray,
                            @"pm2.5":pm25Array,
                            @"pm10":pm10Array,
                            @"o3":o3Array,
                            @"so2":so2Array,
                            @"no2":no2Array,
                            @"co":coArray,
                            @"times":timeArray};
    }
}

- (void)setCityData:(NSArray *)cityData
{
    @autoreleasepool {
        NSMutableArray * aqiArray = [NSMutableArray array];
        NSMutableArray * pm25Array = [NSMutableArray array];
        NSMutableArray * pm10Array = [NSMutableArray array];
        NSMutableArray * so2Array = [NSMutableArray array];
        NSMutableArray * no2Array = [NSMutableArray array];
        NSMutableArray * coArray = [NSMutableArray array];
        NSMutableArray * o3Array = [NSMutableArray array];
        NSMutableArray * timeArray = [NSMutableArray array];
        
        for (NSDictionary * tempDic in cityData) {
            NSDictionary * dic = [[tempDic allValues] firstObject];
            [aqiArray addObject:dic[@"AQI"]];
            [pm25Array addObject:dic[@"PM2_5"]];
            [pm10Array addObject:dic[@"PM10"]];
            [o3Array addObject:dic[@"O3"]];
            [so2Array addObject:dic[@"SO2"]];
            [no2Array addObject:dic[@"NO2"]];
            [coArray addObject:dic[@"CO"]];
            NSTimeInterval time = [dic[@"TIMEPOINT"] integerValue] / 1000;
            NSString * timeString = [RJTools getTimeWithFormat:@"HH时" time:[NSDate dateWithTimeIntervalSince1970:time]];
            [timeArray addObject:timeString];
        }
        _model.cityData = @{@"aqi":aqiArray,
                            @"pm2.5":pm25Array,
                            @"pm10":pm10Array,
                            @"o3":o3Array,
                            @"so2":so2Array,
                            @"no2":no2Array,
                            @"co":coArray,
                            @"times":timeArray};
    }
}
@end
